<?php
namespace common\action;

use Yii;
use yii\base\Action;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use yii\web\Controller;
use backend\components\Utools;
use backend\components\Ftp;
use backend\modules\admin\models\Site;
use backend\modules\admin\models\ReleasePoint;
use common\models\Attachment;

/**
 * 独立动作
 * 上传文件（目前只能是图片）
 * 返回值为一个json字符串
 */
class UploadAction extends Action
{
    public $config;
    public function init()
    {
        //close csrf
        Yii::$app->request->enableCsrfValidation = false;
        //默认设置
        $_config = require(__DIR__ . '/config.php');
        //load config file
        $this->config = ArrayHelper::merge($_config, $this->config);
        parent::init();
    }
    /**
     * 上传文件（图片，视频等）
     * @return string 返回一个json字符串
     */
    protected function Upload()
    {
        $base64 = "upload";
        if(!empty($_GET['action']))
        {
            switch(htmlspecialchars($_GET['action']))
            {
                case 'uploadimage':
                    $config = array(
                        "pathFormat" => $this->config['imagePathFormat'],
                        "maxSize" => $this->config['imageMaxSize'],
                        "allowFiles" => $this->config['imageAllowFiles'],
                        "is_html"=>$this->config['is_html'],
                        "filesPath"=>$this->config['imageFiles'],
                        "urlPrefix"=>$this->config['imageUrlPrefix'],
                        "type"=>'image',
                        "re_type"=>$this->config['re_type'],
                    );
                    $fieldName = $this->config['imageFieldName'];
                    break;
                case 'uploadscrawl':
                    $config = array(
                        "pathFormat" => $this->config['scrawlPathFormat'],
                        "maxSize" => $this->config['scrawlMaxSize'],
                        "oriName" => "scrawl.png",
                        "is_html"=>$this->config['is_html'],
                        "filesPath"=>$this->config['scrawlFiles'],
                        "urlPrefix"=>$this->config['scrawlUrlPrefix'],
                        "type"=>'scrawl',
                    );
                    $fieldName = $this->config['scrawlFieldName'];
                    $base64 = "base64";
                    break;
                case 'uploadvideo':
                    $config = array(
                        "pathFormat" => $this->config['videoPathFormat'],
                        "maxSize" => $this->config['videoMaxSize'],
                        "allowFiles" => $this->config['videoAllowFiles'],
                        "is_html"=>$this->config['is_html'],
                        "filesPath"=>$this->config['videoFiles'],
                        "urlPrefix"=>$this->config['videoUrlPrefix'],
                        "type"=>'video',
                    );
                    $fieldName = $this->config['videoFieldName'];
                    break;
                case 'uploadfile':
                default:
                    $config = array(
                        "pathFormat" => $this->config['filePathFormat'],
                        "maxSize" => $this->config['fileMaxSize'],
                        "allowFiles" => $this->config['fileAllowFiles'],
                        "is_html"=>$this->config['is_html'],
                        "filesPath"=>$this->config['fileFiles'],
                        "urlPrefix"=>$this->config['fileUrlPrefix'],
                        "type"=>'file',
                    );
                    $fieldName = $this->config['fileFieldName'];
                    break;
            }
        }
        else
        {
            //上传图片的配置，从控制器中传来的配置信息
            $config = array(
                "pathFormat" => $this->config['imagePathFormat'],
                "maxSize" => $this->config['imageMaxSize'],
                "allowFiles" => $this->config['imageAllowFiles'],
                "is_html"=>$this->config['is_html'],
                "filesPath"=>$this->config['imageFiles'],
                "urlPrefix"=>$this->config['imageUrlPrefix'],
                "type"=>'image',
                "re_type"=>$this->config['re_type'],
            );
            $fieldName = $this->config['imageFieldName'];
        }
        /* 生成上传实例对象 */
      
        $upload = UploadedFile::getInstanceByName($fieldName);
        
        $ext = $upload->getExtension();
        //$ext = $ext?$ext:'jpg';
        //自动创建文件夹
        $dir = FRONT_PATH."web/uploads/".$config['type'].'/'.date('Ymd')."";
       
       
        if(!file_exists($dir))
        {
            
            @mkdir($dir,0777,true);
        }
        
        $a=time().rand(100000,999999).'.'.$ext;
        $save_a = $config['filesPath'].$a;//保存路径   前台域名/文件夹/文件名
        $file_a = $config['pathFormat'].$a;//文件路径        前台文件夹位置/文件名
        
       
       
        //统一将附件上传到前台资源文件夹中
        //保存成功，则添加返回的信息
       
        if($upload->saveAs($save_a))
        {
            $array = array(
                "error" => 0,
                "state" => "SUCCESS",
                "filepath" => ($config['urlPrefix']?$config['urlPrefix']:'').$file_a,          //返回的地址
                "filename" => $upload->name,          //新文件名
                "original" => $upload->name,       //原始文件名
                "filetype" => $upload->type,      //文件类型
                "fileext" => $ext, //文件扩展名
                "filesize" => $upload->size,          //文件大小
                "uploadtime" =>time(),
                "uploadip" =>  Yii::$app->request->userIP,
                "module" => Yii::$app->request->post('module')?Yii::$app->request->post('module'):0,
                "catid" =>Yii::$app->request->post('catid')?Yii::$app->request->post('catid'):0,
                "userid" => Yii::$app->request->post('userid'),
                "action" => !empty($_GET['action']) ? $_GET['action']:'',
                "re_type" =>$config['re_type'],
            );

           
            //是否配置附件服务器，配置了则把附件上传附件服务器
            /**
             * ******如想上传到附件服务器，必需在配置系统变量中，配置附件服务器ip地址，附件服务器域名，账号，密码。*******
             */
            if(!empty($this->config['atta_server']))
            {
                $ftps = new Ftp();
                $rs = $ftps->connect($this->config['atta_server'],Yii::$app->params['atta_server_account'],Yii::$app->params['atta_server_password']);
                $file = date('Ymd').'/'.time().rand(100000,999999).'.'.$ext;//远程服务器文件夹
                $ftps->chdir($file); //设置文件存放位置
                $ftps->put($file,$save_a,0);//把文件上传到发布点
    
                //修改附件地址为远程服务器上地址
                $array['filepath'] =$config['atta_path'].$file;//新地址
            }
            if($this->config['is_html'] && empty($this->config['atta_server']))
            {
                $ftps = new Ftp();
                $site = Site::findOne(Utools::getSiteid());
                
                $point = ReleasePoint::findOne($site->release_point);
                $release_point=$point;
                if ($ftps->connect($release_point['host'], $release_point['username'], $release_point['password'], $release_point['port'], $release_point['pasv'], $release_point['ssl'])) {
                    
                    // echo $obase_file.'<br>';
                    //echo $file;
                    if ($release_point['path'])
                    {
                        $ftps->chdir($release_point['path']);
                    }

                    //echo $release_point['path'].$file;
                    //$file=$tempfile;
                    //$file = $site_dir.$file;
                    if ($ftps->put($release_point['path'].$file_a, $save_a,0)) {
                        $status = 1;
                    }
                    
                }
            }
        }
        else
        {
           
            $array=  array(
                "error"=>1,
                "state" => "ERROR",       //上传状态，上传成功时必须返回"SUCCESS"
                'url'=>'',
            );
        }
        
        return $array;
        
        /* 返回数据 */
        
    }
    
    public function run()
    {
        if(Yii::$app->request->isPost)
        {
            $data = $this->Upload();           //执行Upload方法
            
            //$data=Utools::array2string($data);      //将返回的数组转换为字符串
            //$this->controller->redirect(['testup/dbadd','data'=>$data]); //使用表单上传图片
            //$this->controller->actionDbadd($data);          //使用swfload上传图片]
            $site=Utools::getSiteid();
            //判断上传的是否为图片
            if(strstr($data['filetype'],'/',true)=='image')
            {
                $sign = 1;
            }
            else
            {
                $sign = 0;
            }
          
            $atta = new Attachment();
            $atta->module = $data['module'];
            $atta->catid = $data['catid'];
            $atta->userid = $data['userid'];
            $atta->filename = $data['filename'];
            $atta->filepath = $data['filepath'];
            $atta->filesize = $data['filesize'];
            $atta->fileext = $data['fileext'];
            $atta->isimage = $sign;
            $atta->uploadtime = $data['uploadtime'];
            $atta->uploadip = $data['uploadip'];
            $atta->siteid = $site;
            $atta->save();
            $aids[] = $atta->aid;
            
            switch($data['re_type'])
            {
                case 'swfupload':
                    if(empty($data['action']))
                    {
                        echo $aids[0].','.$atta->filepath.','.$atta->isimage.','.$atta->filename;       //打印拼接字符串，配合 handlers.js 使用
                    };
                    break;
                case 'normal':
                        echo $aids[0].','.$data['filepath'];
                    break;
                default:
                    break;
 
            }
            
        }
        else
        {
            echo '未提交数据';
        }
    }


}




?>